package com.kafka.producer;

import org.apache.kafka.clients.producer.*;

import java.util.Properties;

/**
 * Created by IntelliJ IDEA.
 * <p>
 * Author: libingyang
 * Date: 2021-02-20 16:53
 */
public class CallBackProducer {


    public static void main(String[] args) {

        Properties props = new Properties();


        // Kafka 服务端的主机名和端口号
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.100.125:9092");

        // key 序列化
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,
                "org.apache.kafka.common.serialization.StringSerializer");

        // value 序列化
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,
                "org.apache.kafka.common.serialization.StringSerializer");

        Producer<String, String> producer = new KafkaProducer(props);

        for (int i = 0; i < 50; i++) {
            producer.send(new ProducerRecord<String, String>("first",

                     "hello world-" + i), new Callback() {

                public void onCompletion(RecordMetadata metadata, Exception exception) {

                   if (exception == null) {

                       System.out.println(metadata.partition()+ "-----"+ metadata.offset());

                   } else {

                       exception.printStackTrace();
                   }
                }

            });
        }

        producer.close();
    }

}
